﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLibrary.Web.Core
{
    public class EntityFactory
    {
        private static Dictionary<string, EntityInfo> _table = new Dictionary<string, EntityInfo>();
 

        /// <summary>
        /// Holds the methods that create the different components.
        /// </summary>
        public class EntityInfo
        {
            public object EntityPrototype;
            public Func<object> RepoCreator;
            public Func<object> ServiceCreator;
            public object RepositorySingleton;
        }


        /// <summary>
        /// Register the entity components
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="entityRepoCreator"></param>
        /// <param name="entityServiceCreator"></param>
        public static void RegisterEntity(object entity, Func<object> entityRepoCreator, Func<object> entityServiceCreator )
        {
            var info = new EntityInfo();
            info.EntityPrototype = entity;
            info.RepoCreator = entityRepoCreator;
            info.ServiceCreator = entityServiceCreator;
            _table[entity.GetType().FullName] = info;
        }


        /// <summary>
        /// Gets an instance of the entity service.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static EntityService<T> GetEntityService<T>() where T : class
        {
            var name = typeof (T).FullName;
            if (!_table.ContainsKey(name))
                return null;

            var info = _table[name];
            var service = (EntityService<T>)info.ServiceCreator();
            if(info.RepositorySingleton == null)
            {
                info.RepositorySingleton = info.RepoCreator();
            }
            var repo = info.RepositorySingleton as EntityRepository<T>;
            service.Repository = repo;
            return service;
        }
    }
}
